package models
import (
	"time"
	"github.com/astaxie/beego/orm"
//	."LiquidMeasurement/lib"
	"github.com/astaxie/beego"
)
type Bed struct {
	Id          	uint64			`orm:"unique;auto"`
	BedNum			string
	Room_			*Room			`orm:"rel(fk)"`
	Department_		*Department		`orm:"rel(fk)"`
	Createtime    	time.Time 		`orm:"type(datetime);auto_now_add" `
	Updatetime    	time.Time 		`orm:"type(datetime);auto_now_add" `
}



type BedResponeModel struct {
	Id          	uint64
	BedNum			string
	Room_			Room
	Department_		Department

}

func init() {
	// 需要在init中注册定义的model
	orm.RegisterModel(new(Bed))
}


//获取本服务器的连接池中的设备
//@return   Beds []Bed   返回Bed的数组
//@return   count int64      数组的数量

func GetBedList ()(models []BedResponeModel,count int64) {
	o := orm.NewOrm()
	bed := new(Bed)
	qs := o.QueryTable(bed)
	count, _ = qs.Count()

	Beds := make([]Bed,count)
	models = make([]BedResponeModel,count)

	//var Beds []Bed
	qs.All(&Beds)
	for index, value := range Beds {
		models[index].Id = value.Id
		models[index].BedNum = value.BedNum
		models[index].Department_ ,_= GetDepartmnetById(value.Department_.Id);
		models[index].Room_ ,_= GetRoomById(value.Room_.Id);
	}
	return models, count
}

//添加床位
//@param u  *Bed      要添加的用户数组结构体
//@return    int64      返回用户的id
//@return    error      返回的错误
func AddBed(u *Bed) (int64, error) {
	o := orm.NewOrm()

//	u.UserPw = Strtomd5(u.UserPw)
	BedID, err := o.Insert(u)
	return BedID, err
}

//通过bedID获取床位数据
//@param 	bedID  int64      床位号
//@return   user   Bed      返回用户的数组
//@return   err	   error      返回的错误
func GetBedByBedID(bedID uint64) (bed BedResponeModel,err error) {
	bed_ := Bed{Id: bedID}
	o := orm.NewOrm()
	err = o.Read(&bed_, "id")
	if err == orm.ErrNoRows {
		beego.Info("查询不到")
		return bed,err
	} else if err == orm.ErrMissPK {
		beego.Info("找不到主键")
		return bed,err
	}
	beego.Info("user get Bed",bed)
	bed.BedNum = bed_.BedNum
	bed.Id = bed_.Id
	bed.Department_,_ = GetDepartmnetById(bed_.Department_.Id)
	bed.Room_ ,_= GetRoomById(bed_.Room_.Id)
	return bed,err
}


//通过BedID删除床位数据
//@param 	BedID   int64      床位的ID
//@return   	 int64      返回删除数据的状态
//@return   err	 error      返回的错误
func DelBedByBedID(BedID uint64) (int64, error) {
	bed := Bed{Id:BedID}
	o := orm.NewOrm()
	err := o.Read(&bed, "id")

	status, err := o.Delete(&bed)
	return status, err
}
//更新床位
//@param 	u   Bed      更新用户的数组结构
//@return   	Bed      返回用户的数据
//@return   err	 error      返回的错误
func UpdateBed(u *Bed) (Bed, error) {
	bed := Bed{Id:u.Id}
	o := orm.NewOrm()
	err := o.Read(&bed, "id")
	if err == orm.ErrNoRows {
		beego.Info("查询不到")
		return bed,err
	} else if err == orm.ErrMissPK {
		beego.Info("找不到主键")
		return bed,err
	}
//	bed.RoomID = u.RoomID
//	bed.Priority = u.Priority

	if u.Department_ != nil{
		bed.Department_ = u.Department_
	}

	u.Updatetime = time.Now()
	if num, err := o.Update(&bed); err == nil {
		beego.Info(num)
	}else{
		beego.Info("Update",err)
	}
	beego.Info("bed",bed)
	return bed, err
}